from py2neo import Graph
import json
import pandas as pd


#   10DKX-71441   taiping
#   10DKX-496481  minping
#   10DKX-100545  nanzhu
#   10.134.157.86:7687
# n4j:
# uri: bolt: // 10.134.157.215: 7687
# username: n4j
# password: jsepc01!
def getLine(DKX_id):
    try:
        DKX_id = "'" + DKX_id + "'"
        graph = Graph('bolt://10.134.157.215:7687', username='neo4j', password='jsepc01!')
        sql = '''
                match p=(a)-[r:SOLID_BUS_LINE|:DOTTED_BUS_LINE]->(b) where r.dkx_id=#{tSbZwycDkxVo.dkxId} 
                return 
                id(a) as s1,
                id(b) as s2,
                labels(a) as s3,
                labels(b) as s4
        '''
        sql = sql.replace('#{tSbZwycDkxVo.dkxId}', DKX_id)
        df = graph.run(sql).to_data_frame()
        return df
    except Exception as e:
        print(e)


def get_tree(dkxid):
    a = getLine(dkxid).values
    tree_node = []
    tree_label = []
    for i in a:
        if i[0] in tree_node:
            if (i[1] in tree_node) == 0:
                tree_node.append(i[1])
                tree_label.append(i[3])
        else:
            tree_node.append(i[0])
            tree_label.append(i[2])
            if (i[1] in tree_node) == 0:
                tree_node.append(i[1])
                tree_label.append(i[3])
    newsub = tree_label.index(['NewSubstation'])
    temp1 = tree_node[newsub]
    temp2 = tree_label[newsub]
    # temp3 = a[newsub]
    tree_node[newsub] = tree_node[0]
    tree_node[0] = temp1
    tree_label[newsub] = tree_label[0]
    tree_label[0] = temp2
    # a[newsub] = a[0]
    # a[0] = temp3
    tree_map = [[0 for i in range(len(tree_node))] for i in range(len(tree_node))]
    for i in a:
        xx = tree_node.index(i[0])
        yy = tree_node.index(i[1])
        tree_map[xx][yy] = 1
        tree_map[yy][xx] = 1

    return tree_node, tree_map, tree_label


if __name__ == '__main__':
    jie = get_tree('10DKX-866945')
    print(len(jie))
    print(jie[-1])

    print(jie[0])
    print(jie)
    jicc = []

    for i in jie[1]:
        cishu = 0
        for j in i:
            if j == 1:
                cishu = cishu + 1
        jicc.append(cishu)

    print(jicc)
    print(len(jicc))
    aaa = 0
    for i in jicc:
        aaa = aaa + i
    print(aaa)
